package com.degratnik.plitki.fragments;

import com.degratnik.plitki.R;
import com.degratnik.plitki.adapters.PlitkiAdapter;
import com.degratnik.plitki.sql.data.Event;

import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ImageView;

public class PlitkiFragment extends Fragment {
	private static final double THIRTY_PERCENTS = 0.3;

	private static final int NUMBER_OF_COLUMNS = 4;

	private static final double TEN_PERCENTS = 0.1;

	private static final float UNDEFINED_COORD = .0f;

	private static final int UNDEFINED_ITEM = -1;

	private static final boolean PROCESS_SCROLLING = false;

	private static final boolean PROCESS_ITEM_CLICK = false;

	private static final boolean STOP_TOUCH_EVENT_PROCESSING = true;

	private static final boolean NOT_ATTACH_TO_ROOT = false;

	private GridView grid;

	private int swap_1 = UNDEFINED_ITEM;
	private int swap_2 = UNDEFINED_ITEM;
	
	private int width = 0;

	private PlitkiAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup parent,
			Bundle state) {
		View v = inflater.inflate(R.layout.plitki, parent, NOT_ATTACH_TO_ROOT);
		grid = (GridView) v.findViewById(R.id.plitkiGrid);
		grid.setNumColumns(NUMBER_OF_COLUMNS);
		
		Display display = getActivity().getWindowManager().getDefaultDisplay();
		Point size = new Point();
		width = display.getWidth();
		
		//TODO move adapter to onCreate
		if (adapter ==null)  adapter = new PlitkiAdapter(getActivity().getApplicationContext());
		
		
		
		grid.setAdapter(adapter);
		grid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View v, int i,
					long arg3) {
				Log.i(PlitkiFragment.class.getName(),
						String.format("Item Click %d", i));
				Plitka fragment = new Plitka();
				fragment.setAdapter(adapter);
				//TODO govnokod -> ActivityForResult
				Plitka.event = (Event) adapter.getItem(i);
				// fragment.setArguments(bundle);
				FragmentTransaction transaction = getActivity()
						.getSupportFragmentManager().beginTransaction();
				String tag = "plitka";
				transaction.replace(R.id.frame, fragment, tag);
				transaction.addToBackStack(tag);
				transaction.commit();
			}

		});
		grid.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View v, int i,
					long arg3) {
				Log.i(PlitkiFragment.class.getName(),
						String.format("Item LONGClick %d", i));
				// remember the first item for swap
				swap_1 = i;
				swap_2 = UNDEFINED_ITEM;
				return STOP_TOUCH_EVENT_PROCESSING; // no item click
			}
		});

		grid.setOnTouchListener(new OnTouchListener() {

			private float down_x = UNDEFINED_COORD;
			private float down_y = UNDEFINED_COORD;
			private float up_x = UNDEFINED_COORD;
			private float up_y = UNDEFINED_COORD;

			@Override
			public boolean onTouch(View v, MotionEvent event) {

				if (event.getAction() == MotionEvent.ACTION_DOWN
						|| event.getAction() == MotionEvent.ACTION_UP) {
					Log.i(PlitkiFragment.class.getName(),
							String.format("grid touch %s", event.toString()));
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						down_x = event.getX();
						down_y = event.getY();
					} else {
						up_x = event.getX();
						up_y = event.getY();
						// if down and up touches are close we process item
						// click
						if (Math.abs(up_x - down_x) < width*TEN_PERCENTS
								&& Math.abs(up_y - down_y) < width*TEN_PERCENTS) {
							swap_1 = UNDEFINED_ITEM;
							swap_2 = UNDEFINED_ITEM;
							return PROCESS_ITEM_CLICK;
						} else {
							// select items for swap and run animation
							float delta_y = up_y - down_y;
							float delta_x = up_x - down_x;
							Log.i(PlitkiFragment.class.getName(), String
									.format("delata x=%f y=%f", delta_x,
											delta_y));
							if (delta_y >= width*THIRTY_PERCENTS) {
								swap_2 = swap_1 + NUMBER_OF_COLUMNS;
							} else if (delta_y <= -width*THIRTY_PERCENTS) {
								swap_2 = swap_1 - NUMBER_OF_COLUMNS;
							} else if (delta_x >= width*THIRTY_PERCENTS) {
								swap_2 = swap_1 + 1;
							} else if (delta_x <= -width*THIRTY_PERCENTS) {
								swap_2 = swap_1 - 1;
							}

							if (swap_1 > 0 && swap_2 > 0) {
								// swap
								adapter.swap(swap_1, swap_2);
								Log.i(PlitkiFragment.class.getName(), String
										.format("swap %d %d", swap_1, swap_2));
								View view = grid.getChildAt(swap_1);
								ImageView image = (ImageView) view
										.findViewById(R.id.image);
								TranslateAnimation animation = new TranslateAnimation(0, width, 0, 0);
								animation.setDuration(500);
								animation.setFillAfter(true);
								animation.setAnimationListener(new AnimationListener() {

											@Override
											public void onAnimationStart(
													Animation animation) {
											}

											@Override
											public void onAnimationRepeat(
													Animation animation) {
											}

											@Override
											public void onAnimationEnd(
													Animation animation) {
												adapter.notifyDataSetChanged();
											}
										});
								image.startAnimation(animation);
								view = grid.getChildAt(swap_2);
								image = (ImageView) view
										.findViewById(R.id.image);
								animation = new TranslateAnimation(0, -width, 0, 0);
								animation.setDuration(500);
								animation.setFillAfter(true);
								animation.setAnimationListener(new AnimationListener() {

											@Override
											public void onAnimationStart(
													Animation animation) {
											}

											@Override
											public void onAnimationRepeat(
													Animation animation) {
											}

											@Override
											public void onAnimationEnd(
													Animation animation) {
												adapter.notifyDataSetChanged();
											}
										});
								image.startAnimation(animation);

							}
							swap_1 = UNDEFINED_ITEM;
							swap_2 = UNDEFINED_ITEM;
							return STOP_TOUCH_EVENT_PROCESSING; // no item click
																// and long
							// it kill default fast scrolling
						}
					}
				}

				return PROCESS_SCROLLING;
			}
		});
		
		
		
		return v;
	}
	

	
	
}
